package cn.amebius.simpledocker.service.impl;

import cn.amebius.simpledocker.entity.po.UserPo;
import cn.amebius.simpledocker.exception.DataErrorException;
import cn.amebius.simpledocker.exception.LoginFailException;
import cn.amebius.simpledocker.exception.OperationErrorException;
import cn.amebius.simpledocker.exception.SystemErrorException;
import cn.amebius.simpledocker.mapper.UserMapper;
import cn.amebius.simpledocker.service.LoginService;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 登录服务实现类
 * @author 阿伟
 * @date 2023/7/27 20:07
 */
@Slf4j
@Service

public class LoginServiceImpl implements LoginService {


    @Autowired
    UserMapper userMapper;


    @Override
    public String login(String username, String password) {
        UserPo userPo = userMapper.selectByUsername(username);
        if (userPo == null) {
            log.info("用户登录：{}登录失败，用户不存在",username);
            throw new LoginFailException("登录失败，用户不存在");
        } else if (!userPo.getPassword().equals(password)) {
            log.info("用户登录:{}登录失败，密码错误",username);
            throw new LoginFailException("登录失败，密码错误");
        } else {
            StpUtil.login(userPo.getId());
            log.info("用户登录:id = {}登录成功,token = {}",userPo.getId(),StpUtil.getTokenValue());
            return StpUtil.getTokenValueByLoginId(userPo.getId());
        }
    }

    @Override
    public void logout() {
        log.info("用户登出:id = {}登出",StpUtil.getLoginIdDefaultNull());
        StpUtil.logout();
    }

    @Override
    public void reset(String oldPassword, String newPassword) {
        Integer userId = (Integer) StpUtil.getLoginId();
        UserPo userPo = userMapper.selectById(userId);
        if (userPo == null) {
            log.error("用户改密:id = {}未找到账号",userId);
            throw new DataErrorException("数据异常：用户账号丢失");
        } else if (!userPo.getPassword().equals(oldPassword)) {
            log.info("用户改密: id = {}密码错误",userId);
            throw new OperationErrorException("旧密码错误");
        } else if (userPo.getPassword().equals(newPassword)) {
            log.info("用户改密: id = {}新旧密码相同",userId);
            throw new OperationErrorException("新旧密码相同");
        } else if (userMapper.updatePasById(newPassword,userId) == 0) {
            log.error("用户改密:id = {}修改密码错误",userId);
            throw new SystemErrorException("修改密码失败");
        }
    }


}
